package crp.services.api.graphql.loaders;

import com.qwlabs.lang.C2;
import crp.core.academic.app.AcademicService;
import crp.core.academic.domain.models.AcademicTermEntity;
import crp.core.space.app.SpaceService;
import crp.core.space.domain.models.SpaceEntity;
import crp.services.api.graphql.models.AcademicTermPayload;
import crp.services.api.graphql.models.SpacePayload;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

@ApplicationScoped
public class SpaceFetcher {
    private final SpaceService spaceService;

    @Inject
    public SpaceFetcher(SpaceService spaceService) {
        this.spaceService = spaceService;
    }

    public List<SpacePayload> fetch(List<String> ids) {
        Map<String, SpacePayload> mapping = C2.map(spaceService.spaceSearcher().findByIds(ids),
                SpaceEntity::getId,
                SpacePayload::of);
        return C2.list(ids, mapping::get);
    }

    public <S> List<SpacePayload> fetch(List<S> sources, Function<S, String> idMapper) {
        Set<String> ids = C2.set(sources, idMapper, Objects::nonNull);
        Map<String, SpacePayload> mapping = C2.map(spaceService.spaceSearcher().findByIds(ids),
                SpaceEntity::getId,
                SpacePayload::of);
        return C2.list(sources, source ->
                Optional.ofNullable(idMapper.apply(source))
                        .map(mapping::get)
                        .orElse(null));
    }
}
